/*jslint vars: true, forin: true, plusplus: true */
/*global angular: false, engine: false, probe: false, $: false*/
probe.controller("auth", function ($scope, $location) {
	'use strict';
	$scope.enterToPanel = function () {
		$location.path("/panel");
	};

});

probe.controller("MainInterface", function ($window, $location, $scope, $interval, $rootScope, Engine) {
	'use strict';
	$rootScope.pos = [];
	$rootScope.mask = function (color) {
		var mask$ = $("#mask").show();
		color: mask$.css("background-color", color);
	};
	$rootScope.deMask = function () {
		$("#mask").hide().css("background-color", "transparent");
	};
	$rootScope.steps = [];

	$scope.isReadonly = true;

	var refreshLocation;
	(refreshLocation = function () {
		$scope.iframe_href = $window[0].location.href;
	})();

	var timer_id = $interval(refreshLocation, 500);

	$scope.modifyLocation = function () {
		$interval.cancel(timer_id);
		$scope.isReadonly = false;
	};

	$scope.fixLocation = function () {
		$interval.cancel(timer_id);
		$scope.isReadonly = true;
		timer_id = $interval(refreshLocation, 500);
	};

	$scope.gotoLocation = function (e) {
		$interval.cancel(timer_id);
		if (e.which === 1 || e.which === 13) {
			$window[0].location.href = $scope.iframe_href;
			$scope.fixLocation();
		}
	};

	$scope.refreshIframe = function () {
		$window[0].location.reload();
	};

	//toggle panel logic
	//窗口展开收紧
	var flagPanelactive = true;
	$scope.togglePanel = function () {
		flagPanelactive = !flagPanelactive;
	};
	$scope.isPanelActive = function () {
		//if it is not active we want to add a .close class to it
		if (!flagPanelactive) {
			return "close";
		}
	};

	$scope.isMask = $rootScope.isMask;

	$rootScope.hasHEAD = function () {
		return Engine.hasHEAD();
	};

	$scope.deleteStep = function (index) {
		var process = Engine.HEAD();
		process.deleteStep(index);
		$rootScope.steps = process.stepsToJson();
	};

	$scope.moveStepDown = function (index) {
		var process = Engine.HEAD();
		process.moveStepDown(index);
		$rootScope.steps = process.stepsToJson();
	};

	$scope.moveStepUp = function (index) {
		var process = Engine.HEAD();
		process.moveStepUp(index);
		$rootScope.steps = process.stepsToJson();
		console.log($rootScope.steps);
	};

	$rootScope.title = function () {
		if (!$rootScope.hasHEAD()) {
			return "打开或创建";
		} else if ($rootScope.isPlaying) {
			return $rootScope.playStatus + "：" + $rootScope.process.loop + " / " + $rootScope.process.loops;
		} else {
			return "正在编辑";
		}
	};
});

probe.controller("MainMenu", function () {
	'use strict';
});

probe.controller("PlayerBar", function ($scope, Engine, Player, $rootScope, $location) {
	'use strict';
	$rootScope.isPlaying = false;

	$scope.play = function () {
		$rootScope.isDebuging = false;
		$location.path("/panel");
		$rootScope.mask("rgba(0,0,0,0.35)");
		Player.play();
		$rootScope.isPlaying = true;
		$scope.status = "play";
		$rootScope.playStatus = "运行";
	};

	$scope.pause = function () {
		Player.pause();
		$scope.status = "pause";
		$rootScope.playStatus = "暂停";
	};

	$scope.stop = function () {
		$rootScope.isDebuging = false;
		$rootScope.deMask();
		Player.stop();
		$rootScope.isPlaying = false;
	};

	$scope.reset = function () {
		$rootScope.isDebuging = false;
		$rootScope.counter = $rootScope.process.getCounter();
		Player.reset();
	};

	$scope.step = function () {
		$rootScope.isDebuging = true;
		Player.step();
		$rootScope.counter = $rootScope.process.getCounter();
	};
	$scope.iframe = {
		width: function (val) {
			if(angular.isNumber(val) && val > 0){
				$rootScope.iframe.width = val;
			}
			return $rootScope.iframe.width;
		},
		height: function (val) {
			if(angular.isNumber(val) && val > 0){
				$rootScope.iframe.height = val;
			}
			return $rootScope.iframe.height;
		}
	}
});

probe.controller("ToolBar", function ($rootScope, $scope, $http) {
	'use strict';
	$scope.save = function () {
		var process = {
			process: $rootScope.process.toJson(),
			steps: $rootScope.process.stepsToJson()
		};
		console.log(process);
		$http.post("http://192.168.1.112:8080/TestWeb-Foundation/probe/process/", process).success(function () {

		});

	};

	$scope.isPlaying = function () {
		return $rootScope.isPlaying;
	};

	$scope.destroyProgram = function () {
		var process = $rootScope.process.destroyProgram();
		$rootScope.steps = process.stepsToJson();
	};
});

probe.controller("DictionaryOpen", function ($location, $http, $scope, $rootScope, $stateParams, Engine) {
	'use strict';
	$scope.action = $stateParams.action;
	if (!angular.isDefined($rootScope.pos[0])) {
		$rootScope.pos[0] = {
			left: 0,
			top: 0
		};
	}
	$scope.pos = $rootScope.pos[0];

	// TODO更改地址
	$http.get("http://115.29.147.58:8080/TestWeb-Foundation/probe/dictionary/list").success(function (response) {
		$scope.dictionaries = response.data.dictionaries;
	});

	$scope.selectDictionary = function (dictionaryid) {
		$http.get("http://115.29.147.58:8080/TestWeb-Foundation/dictionary/" + dictionaryid).success(function (response) {
			var options = {
				ID: response.data.dictionary.dictionaryid,
				name: response.data.dictionary.name,
				comment: response.data.dictionary.comment,
				createtime: response.data.dictionary.createtime,
				updatetime: response.data.dictionary.updatetime,
				assignment: angular.fromJson(response.data.dictionary.assignment),
				field: angular.fromJson(response.data.dictionary.field)
			};

			var newDictionary = Engine.create("Dictionary", options);
			$rootScope.dictionaryBuffer = newDictionary;
		});

		$location.path("/panel/process/add");
	};
});

probe.controller("ProcessDialog", function ($http, $scope, $location,
	$rootScope, $window, $stateParams, Engine) {
	'use strict';
	if (!angular.isDefined($rootScope.pos[1])) {
		$rootScope.pos[1] = {
			left: 0,
			top: 0
		};
	}
	$scope.pos = $rootScope.pos[1];
	$scope.getLocation = function () {
		$scope.options.origin = $window[0].location.href;
	};

	$scope.isCreate = function () {
		return $stateParams.action !== "modify";
	};

	// 新建状态
	if ($scope.isCreate()) {
		$scope.options = {
			origin: $window[0].location.href,
			name: $window[0].document.title,
			loops: 100
		};
	} else {
		$scope.options = Engine.HEAD().toOptions();
	}

	$scope.createProcess = function () {
		$rootScope.process = Engine.HEAD(Engine.create("Process", $scope.options));
		$rootScope.steps = $rootScope.process.stepsToJson();
		$location.path("panel");

		if ($rootScope.dictionaryBuffer) {
			$rootScope.process.addDictionary($rootScope.dictionaryBuffer);
			delete $rootScope.dictionaryBuffer;
		}

		$rootScope.process.setupCallback("success", function () {
			$rootScope.deMask();
			$rootScope.isPlaying = false;
		});

		$rootScope.process.setupCallback("before_run", function () {
			$rootScope.counter = $rootScope.process.getCounter();
		});

		window.p = $rootScope.process;

	};

	$scope.modifyProcess = function () {
		$rootScope.process = Engine.HEAD().modify($scope.options);
		$location.path("panel");
	};

	$scope.loops = function (newLoops) {
		return angular.isDefined(newLoops) ? ($scope.options.loops = parseInt(newLoops, 0)) : $scope.options.loops;
	};

});

probe.controller("ProcessOpen", function ($http, $scope, $rootScope) {
	'use strict';
	if (!angular.isDefined($rootScope.pos[2])) {
		$rootScope.pos[2] = {
			left: 0,
			top: 0
		};
	}
	$scope.pos = $rootScope.pos[2];

	// TODO更改地址
	$http.get("http://192.168.1.112:8080/TestWeb-Foundation/probe/process/list").success(function (response) {
		$scope.processes = response.data.processes;
	});
});


/**
 * 步骤创建与编辑控制器
 */
probe.controller("StepDialog", function ($http, $scope, $location, $rootScope, $stateParams, $filter, Engine, Capture) {
	'use strict';
	if (angular.isUndefined($rootScope.process)) {
		$location.path("/panel");
	}

	if (!angular.isDefined($rootScope.pos[3])) {
		$rootScope.pos[3] = {
			left: 0,
			top: 0
		};
	}
	$scope.pos = $rootScope.pos[3];
	$scope.isCreate = function () {
		return $stateParams.action !== "modify";
	};

	if ($scope.isCreate()) {
		$scope.options = {
			name: "STEP #" + Engine.HEAD().getLength(),
			type: "DelayStep",
			delay: 3000,
			object: "",
			action: "click",
			param: {},
			updatetime: (new Date()).getTime()
		};
	} else {
		$scope.options = Engine.HEAD().getStep($stateParams.index).toOptions();
	}

	$scope.hasDictionary = function () {
		return $rootScope.process.hasDictionary();
	};

	if ($scope.hasDictionary()) {
		$scope.fields = $rootScope.process.getDictionary().getKeys();
	}

	// Delay存取器，用于转换输入的string为number
	$scope.delay = function (newDelay) {
		return angular.isDefined(newDelay) ? ($scope.options.delay = parseInt(newDelay, 0)) : $scope.options.delay;
	};

	// Type存取器，用于后面参数的联动修改
	$scope.type = function (newType) {
		if (angular.isDefined(newType)) {
			$scope.options.type = newType;
			delete $scope.options.condition;
			$scope.options.delay = 3000;
		}
		return $scope.options.type;
	};

	// Action存取器
	$scope.action = function (newAction) {
		if (angular.isDefined(newAction)) {
			var opts = $scope.options;
			opts.action = newAction;
			switch (newAction) {
			case "val":
				opts.param = {
					type: "direct",
					value: ""
				};
				break;
			case "scroll":
				opts.param = {
					top: 0,
					left: 0
				};
				break;
			default:
				opts.param = {};
				break;
			}
		}

		return $scope.options.action;
	};

	$scope.hasParam = function () {
		var action = $scope.options.action;
		return action === 'val' || action === 'scroll';
	};

	$scope.appendStepTo = function () {
		var newStep, process = Engine.HEAD();
		newStep = Engine.create($scope.options.type, $scope.options);
		if ($scope.isCreate()) {
			if ($stateParams.index !== "") {
				process.insertStep(parseInt($stateParams.index, 0), newStep);
			} else {
				process.addStep(newStep)
			}
		} else {
			process.replaceStep(parseInt($stateParams.index, 0), newStep);
		}
		$rootScope.steps = process.stepsToJson();
		$location.path("/panel");
	};

	$scope.catchHTML = function () {
		$rootScope.isCapturing = true;
		Capture.watchHTML(function (cssPath) {
			$rootScope.isCapturing = false;
			$scope.options.object = cssPath;
		});
	};

	$scope.updatetime = function () {
		return $filter('date')($scope.options.updatetime, "yyyy-MM-dd");
	};

	$scope.selectorLength = function () {
		if ($scope.options.object === "") {
			return 0;
		} else {
			return $($scope.options.object, window[0].document).length;
		}
	};

});
probe.controller("About", function ($scope, $rootScope) {
	if (!angular.isDefined($rootScope.pos[4])) {
		$rootScope.pos[4] = {
			left: 0,
			top: 0
		};
	}
	$scope.pos = $rootScope.pos[4];
});
probe.controller('Frame', function ($scope, $rootScope) {
	$rootScope.iframe = {
		width: document.body.clientWidth,
		height: document.body.clientHeight
	};
});
